package myNewProject.utils;

import myNewProject.App;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

public class MySQLUtil {
    private static final String MySQL_URL = App.CONFIG.getProperty("MySQLUrl");
    private static final String MySQL_USER = App.CONFIG.getProperty("MySQLUser");
    private static final String MySQL_PASSWORD = App.CONFIG.getProperty("MySQLPassword");
    private static Connection connection;

    public static Connection connect() {
        System.out.println("正在链接数据库");
        Statement statement = null;
        try {
            connection = DriverManager.getConnection(MySQL_URL, MySQL_USER, MySQL_PASSWORD);
            statement = connection.createStatement();
            String query = "truncate table parsedResult;";
            statement.executeUpdate(query);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                if (statement != null && !statement.isClosed()) {
                    statement.close();
                }
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        return connection;
    }

    public static void close() {
        try {
            if (connection != null && !connection.isClosed()) {
                connection.close();
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        System.out.println("已关闭数据库链接。");
    }
}
